import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => {
    // 尝试从localStorage加载用户信息
    let userInfo = null;
    try {
      const storedInfo = localStorage.getItem('userInfo');
      if (storedInfo) {
        userInfo = JSON.parse(storedInfo);
        console.log('Pinia store从localStorage初始化用户信息:', userInfo);
      }
    } catch (e) {
      console.error('加载localStorage用户信息失败:', e);
    }
    
    return {
      sidebarCollapsed: false,
      userInfo: userInfo,
    }
  },

  getters: {
    userName: (state) => state.userInfo?.name || '未登录',
    userAvatar: (state) => state.userInfo?.avatar,
    isAdmin: (state) => state.userInfo?.username === 'admin',
  },

  actions: {
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo
      // 同步到localStorage
      try {
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        console.log('用户信息已同步到localStorage');
      } catch (e) {
        console.error('保存用户信息到localStorage失败:', e);
      }
    },

    clearUserInfo() {
      this.userInfo = null
      // 清除localStorage中的用户信息
      try {
        localStorage.removeItem('userInfo');
        console.log('已清除localStorage中的用户信息');
      } catch (e) {
        console.error('清除localStorage用户信息失败:', e);
      }
    },
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app-store',
        storage: localStorage,
      },
    ],
  },
}) 